from django.shortcuts import render_to_response

from login.models import LogInForm, ErrorList

from django.http import HttpResponsePermanentRedirect
from django.core.urlresolvers import reverse

from django.contrib.auth import authenticate, login, logout

def user_login(request):
    """
    Show user login form and validate input.
    """
    if request.user.is_authenticated():
        return HttpResponsePermanentRedirect(reverse('url-home'))
    else:
        if request.method == 'POST':
            form = LogInForm(request.POST, error_class=ErrorList)
            
            if form.is_valid():
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
                
                user = authenticate(username=username, password=password)
                
                if user is not None:
                    if user.is_active:
                        login(request, user)
                        
                        return HttpResponsePermanentRedirect(reverse('url-notes'))
                    else:
                        error_msg = u'Disabled account.'
                else:
                    error_msg = u'Invalid login.'
                
                return render_to_response('login/base_login.html', { 'form': form, 'error': error_msg })
        else:
            form = LogInForm()
        
        return render_to_response('login/base_login.html', { 'form': form, })
